package com.yzx.lifeassistants.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

import com.balysv.materialripple.MaterialRippleLayout;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.base.BaseApplication;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.CacheUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.RoundedImageView;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 用户设置
 * @author: yzx
 * @time: 2016-4-24 下午3:13:10
 */
@SuppressLint("InflateParams")
public class UserSettingAtivity extends BaseActivity implements OnClickListener {

	private ImageButton backBtn;// 返回按钮
	private RelativeLayout userNameRL;// 用户名
	private TextView userNameTV;// 用户名
	private RelativeLayout avatarRL;// 头像
	private RoundedImageView avatarIV;// 头像
	private RelativeLayout nickRL;// 昵称
	private TextView nickTV;// 昵称
	private RelativeLayout sexRL;// 性别
	private TextView sexTV;// 性别
	private TextView modifyPswTV;// 修改密码

	private CircularLoadingDialog dialog;// 加载框

	private ActionSheetDialog sexDialog;// 性别选择弹框
	private ActionSheetDialog picDialog;// 图片选择弹框
	private File tempFile;// 头像缓存
	private Bitmap bitmap;// 头像
	private String dateTime;// 拍照时间
	private String iconUrl;// 头像Url

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_setting);
		initView();
		setListener();
		initMaterialRipple();
		initSheetDialog();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.user_setting_back_btn);
		userNameRL = (RelativeLayout) findViewById(R.id.user_setting_username_rl);
		userNameTV = (TextView) findViewById(R.id.user_setting_username_tv);
		avatarRL = (RelativeLayout) findViewById(R.id.user_setting_icon_rl);
		avatarIV = (RoundedImageView) findViewById(R.id.user_setting_icon_image);
		nickRL = (RelativeLayout) findViewById(R.id.user_setting_nick_rl);
		nickTV = (TextView) findViewById(R.id.user_setting_nick_tv);
		sexRL = (RelativeLayout) findViewById(R.id.user_setting_sex_rl);
		sexTV = (TextView) findViewById(R.id.user_setting_sex_tv);
		modifyPswTV = (TextView) findViewById(R.id.user_setting_modefy_psw_tv);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		avatarRL.setOnClickListener(this);
		nickRL.setOnClickListener(this);
		sexRL.setOnClickListener(this);
		modifyPswTV.setOnClickListener(this);
	}

	/**
	 * 
	 * @Description: 瓷砖特效
	 */
	private void initMaterialRipple() {
		List<View> views = new ArrayList<View>();
		views.add(userNameRL);
		views.add(avatarRL);
		views.add(nickRL);
		views.add(sexRL);
		views.add(modifyPswTV);
		for (View view : views) {
			// 动态特效
			MaterialRippleLayout
					.on(view)
					.rippleColor(
							Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
					.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
					.create();
		}

	}

	/**
	 * 
	 * @Description: 初始化选择性别/图片来源弹框
	 */
	private void initSheetDialog() {
		final String[] stringItems = { "男性", "女性" };
		sexDialog = new ActionSheetDialog(this, stringItems, null);
		sexDialog.title("请选择您的性别~")//
				.titleTextSize_SP(14.5f);
		sexDialog.setOnOperItemClickL(new OnOperItemClickL() {
			@Override
			public void onOperItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (2 == position) {

				} else {
					dialog.show();
					if (0 == position) {
						GlobalParams.userInfo.setSex(false);
					} else {
						GlobalParams.userInfo.setSex(true);
					}
					GlobalParams.userInfo.update(UserSettingAtivity.this,
							GlobalParams.userInfo.getObjectId(),
							new UpdateListener() {

								@Override
								public void onSuccess() {// 修改成功
									LogcatUtils.i("修改性别成功");
									dialog.dismiss();
									showToast("修改性别成功~", true);
									if (GlobalParams.userInfo.getSex()) {
										sexTV.setText("女");
									} else {
										sexTV.setText("男");
									}
								}

								@Override
								public void onFailure(int code, String message) {// 修改失败
									LogcatUtils.e("修改性别失败：" + code + " "
											+ message);
									GlobalParams.userInfo
											.setSex(!GlobalParams.userInfo
													.getSex());
									dialog.dismiss();
									switch (code) {
									case 9010: {// 网络超时
										showToast("网络超时，请检查您的手机网络~", false);
										break;
									}
									case 9016: {// 无网络连接，请检查您的手机网络
										showToast("无网络连接，请检查您的手机网络~", false);
										break;
									}
									default: {
										showToast("修改失败，请重试~", false);
										break;
									}
									}
								}
							});
				}
				sexDialog.dismiss();
			}
		});
		final String[] picItems = { "相册选取", "相机拍照" };
		picDialog = new ActionSheetDialog(this, picItems, null);
		picDialog.title("请选择图片来源~")//
				.titleTextSize_SP(14.5f);
		picDialog.setOnOperItemClickL(new OnOperItemClickL() {
			@Override
			public void onOperItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (2 == position) {
					picDialog.dismiss();
				} else {
					if (0 == position) {
						picDialog.dismiss();
						Date date1 = new Date(System.currentTimeMillis());
						dateTime = date1.getTime() + "";
						getAvataFromAlbum();
					} else {
						picDialog.dismiss();
						Date date = new Date(System.currentTimeMillis());
						dateTime = date.getTime() + "";
						getAvataFromCamera();
					}
				}
			}
		});
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		userNameTV.setText(GlobalParams.userInfo.getUsername());
		// 昵称
		nickTV.setText(GlobalParams.userInfo.getNick());
		// 性别
		if (GlobalParams.userInfo.getSex() != null
				&& GlobalParams.userInfo.getSex()) {
			sexTV.setText("女");
		} else {
			sexTV.setText("男");
		}
		// 头像
		BmobFile avatarFile = GlobalParams.userInfo.getAvatar();
		if (null != avatarFile) {
			ImageLoader.getInstance().displayImage(
					avatarFile.getFileUrl(this),
					avatarIV,
					BaseApplication.getInstance().getOptions(
							R.drawable.user_icon_default_main),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
						}
					});
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_setting_back_btn: {// 返回
			setResult(1234);
			finish();
			break;
		}
		case R.id.user_setting_icon_rl: {// 修改头像
			picDialog.show();
			break;
		}
		case R.id.user_setting_nick_rl: {// 修改昵称
			editNick();
			break;
		}
		case R.id.user_setting_sex_rl: {// 修改性别
			sexDialog.show();
			break;
		}
		case R.id.user_setting_modefy_psw_tv: {// 修改密码
			modifyPwd();
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 从相册获取
	 */
	protected void getAvataFromAlbum() {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, CommonConstant.REQUESTCODE_PHOTO_ALBUM);
	}

	/**
	 * 
	 * @Description: 从拍照获取
	 */
	protected void getAvataFromCamera() {
		File f = new File(CacheUtils.getCacheDirectory(this, true, "icon")
				+ dateTime);
		if (f.exists()) {
			f.delete();
		}
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Uri uri = Uri.fromFile(f);
		Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);

		startActivityForResult(camera, CommonConstant.REQUESTCODE_PHOTO_CAMERA);
	}

	/**
	 * 
	 * @Description: 判断存储卡是否可以用
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * @Description: 修改昵称
	 */
	private void editNick() {
		Intent intent = new Intent(this, EditUserNickActivity.class);
		startActivityForResult(intent, CommonConstant.REQUESTCODE_EDIT_NICK);
	}

	/**
	 * 
	 * @Description: 修改密码
	 */
	private void modifyPwd() {
		Intent intent = new Intent(this, ModifyPwdActivity.class);
		startActivity(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == CommonConstant.REQUESTCODE_EDIT_NICK) {

			if (resultCode == CommonConstant.RESULTCODE_EDIT_NICK_OK) {
				// 修改昵称成功
				nickTV.setText(GlobalParams.userInfo.getNick());
				showToast("更改昵称成功~", true);

			} else if (resultCode == CommonConstant.RESULTCODE_EDIT_NICK_CANCEL) {
				// 取消修改昵称
				LogcatUtils.i("已取消更改昵称");

			}
		}

		if (resultCode == Activity.RESULT_OK) {
			// 访问相册
			if (requestCode == CommonConstant.REQUESTCODE_PHOTO_ALBUM) {
				if (data != null) {
					// 得到图片的全路径
					Uri uri = data.getData();
					crop(uri);
				}
			}
			// 访问相机
			if (requestCode == CommonConstant.REQUESTCODE_PHOTO_CAMERA) {

				if (hasSdcard()) {
					String files = CacheUtils.getCacheDirectory(this, true,
							"icon") + dateTime;
					tempFile = new File(files);
					if (tempFile.exists() && tempFile.length() > 0) {
						Uri uri = Uri.fromFile(tempFile);
						crop(uri);
					} else {

					}
				} else {
					showToast("未找到存储卡，无法存储照片！", false);
				}
			}
			// 图片裁剪
			if (requestCode == CommonConstant.REQUESTCODE_PHOTO_CUT) {

				try {
					bitmap = data.getParcelableExtra("data");
					iconUrl = saveToSdCard(bitmap);
					avatarIV.setImageBitmap(bitmap);
					updateIcon(iconUrl);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 
	 * @Description: 切图
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, CommonConstant.REQUESTCODE_PHOTO_CUT);
	}

	/**
	 * 
	 * @Description: 把图片保存到sdcard
	 */
	private String saveToSdCard(Bitmap bitmap) {
		String files = CacheUtils.getCacheDirectory(this, true, "icon")
				+ dateTime + "_12.jpg";
		File file = new File(files);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file.getAbsolutePath();
	}

	/**
	 * 
	 * @Description: 更新头像
	 */
	private void updateIcon(String avataPath) {
		if (avataPath != null) {
			final BmobFile file = new BmobFile(new File(avataPath));
			dialog.show();
			file.upload(this, new UploadFileListener() {

				@Override
				public void onSuccess() {// 上传成功
					dialog.dismiss();
					GlobalParams.userInfo.setAvatar(file);
					dialog.show();
					GlobalParams.userInfo.update(UserSettingAtivity.this,
							new UpdateListener() {

								@Override
								public void onSuccess() {// 更新成功
									dialog.dismiss();
									LogcatUtils.i("更改头像成功");
									showToast("更改头像成功~", true);
								}

								@Override
								public void onFailure(int code, String message) {// 更新失败
									LogcatUtils.e("更改头像失败：" + code + " "
											+ message);
									dialog.dismiss();
									switch (code) {
									case 9010: {// 网络超时
										showToast("网络超时，请检查您的手机网络~", false);
										break;
									}
									case 9016: {// 无网络连接，请检查您的手机网络

										showToast("无网络连接，请检查您的手机网络~", false);
										break;
									}
									default: {
										showToast("更改头像失败，请重试~", false);
										break;
									}
									}
								}
							});
				}

				@Override
				public void onFailure(int code, String message) {// 上传失败
					dialog.dismiss();
					LogcatUtils.e("上传头像失败：" + code + " " + message);
					switch (code) {
					case 9010: {// 网络超时
						showToast("网络超时，请检查您的手机网络~", false);
						break;
					}
					case 9016: {// 无网络连接，请检查您的手机网络
						showToast("无网络连接，请检查您的手机网络~", false);
						break;
					}
					default: {
						showToast("更改头像失败，请重试~", false);
						break;
					}
					}
				}
			});
		}
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.user_setting_top_rl);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.user_setting_top_rl);
		}

	}
}
